const User = require("../model/user.model");
const Category = require("../model/Information.model");
// 使用模糊查询需要先引入Op
const seq = require("sequelize");
const Member = require("../model/member.model");
const Op = seq.Op;

class UserService {
    // 创建用户
    async createUser(data) {
        // 插入数据
        // await表达式: promise对象的值
        const res = await User.create(data);
        // console.log(res)
        return res.dataValues;
    }

    //获取用户信息
    async getUerInfo({id, user_name, password, is_admin}) {
        const whereOpt = {};

        id && Object.assign(whereOpt, {id});
        user_name && Object.assign(whereOpt, {user_name});
        password && Object.assign(whereOpt, {password});
        is_admin && Object.assign(whereOpt, {is_admin});

        const res = await User.findOne({
            where: whereOpt,
        });

        return res ? res.dataValues : null;
    }

    //根据id 更新用户信息
    async updateById({id, password, is_admin, nick_name,is_vip,money}) {
        const whereOpt = {id};
        const newUser = {};
        nick_name && Object.assign(newUser, {nick_name});
        password && Object.assign(newUser, {password});
        money && Object.assign(newUser, {money});
        is_admin + "" && Object.assign(newUser, {is_admin});
        is_vip + "" && Object.assign(newUser, {is_vip});

        const res = await User.update(newUser, {where: whereOpt});
        return res[0] > 0;
    }

    // 用户列表
    async findUsers({pageNum, pageSize, nick_name}) {
        const offset = (pageNum - 1) * pageSize;

        const whereOpt = {};

        nick_name && Object.assign(whereOpt, {nick_name: {[Op.like]: `%${nick_name}%`}});
        const {count, rows} = await User.findAndCountAll({
            offset: offset,
            limit: pageSize * 1,
            where: whereOpt,
            order: [["createdAt", "DESC"]],
        });
        return {
            pageNum,
            pageSize,
            total: count,
            list: rows,
        };
    }

    // 删除用户
    async delUser(id) {
        return await User.destroy({
            where: {id},
        });
    }

    async updateUserMoney(money,id){
        const res = await User.update({money: seq.literal('money + '+ money)}, {
            where: {id}
        });
        return res[0] > 0;
    }

    // 提现
    async withdraw({money, id}) {
        const res = await User.update({money: seq.literal('money - '+ money)}, {
            where: {id}
        });
        return res[0] > 0;
    }
}

module.exports = new UserService();
